import { Component, Input, Injector, ViewChild } from '@angular/core';
import { NzDrawerRef } from 'ng-zorro-antd';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
import {
  ColumnInfoEditDto,
  GetDataComboItemDtoOfInt64,
  CreateOrUpdateColumnInfoDto,
  ColumnInfoServiceProxy,
  GetEnumValuesListDto,
} from '@abp/service-proxies/service-proxies';
import { AppComponentBase } from '@abp/components';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';

@Component({
  selector: 'create-or-edit-cloumnDrawer',
  templateUrl: './create-or-edit-cloumn.component.html',
  styleUrls: ['./create-or-edit-cloumn.component.less'],
})
export class CreateOrEditCloumnComponent extends AppComponentBase {
  @Input() id?: number;
  cloumnForm: FormGroup;
  isLoadingBtn = false;

  cloumn: ColumnInfoEditDto = new ColumnInfoEditDto();
  subscriptionVersion = '';

  constructor(
    injector: Injector,
    private drawerRef: NzDrawerRef,
    private fb: FormBuilder,
    private _columnService: ColumnInfoServiceProxy,
  ) {
    super(injector);
  }

  ngOnInit() {
    this.cloumnForm = this.fb.group({
      title: [null, [Validators.required]],
      maxItemCount: [null],
      subscriptionVersion: [null],
      url: [null],
      description: [null],
      introduction: [null],
    });

    this._columnService.getColumnInfoForEdit(this.id).subscribe(result => {
      console.log(this.cloumn);
      this.cloumn = result.columnInfo;
      console.log(this.cloumn);
      if (this.cloumn.isFooterNav) {
        this.subscriptionVersion = 'Bottom';
      } else if (this.cloumn.isHeaderNav) {
        this.subscriptionVersion = 'Top';
      }
    });
  }

  parentSelectedCloumnChange(event: GetDataComboItemDtoOfInt64) {
    this.cloumn.parentId = event == null ? undefined : event.value;
  }

  typeSelectedValueChange(event: GetEnumValuesListDto) {
    this.cloumn.columnType = event == null ? 0 : event.value;
  }

  close(): void {
    this.drawerRef.close(false);
  }

  submitForm() {
    for (const i in this.cloumnForm.controls) {
      this.cloumnForm.controls[i].markAsDirty();
      this.cloumnForm.controls[i].updateValueAndValidity();
    }

    if (this.cloumnForm.valid) {
      console.log(this.cloumn);
      this.isLoadingBtn = true;
      const input = new CreateOrUpdateColumnInfoDto();
      input.columnInfo = this.cloumn;
      this._columnService
        .createOrUpdateColumnInfo(input)
        .pipe(finalize(() => (this.isLoadingBtn = false)))
        .subscribe(() => {
          this.notify.success('操作成功！');
          this.drawerRef.close(true);
        });
    }
  }
}
